package top.jle.wx.proxy.config;

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.models.*;
import io.swagger.v3.oas.models.annotations.OpenAPI31;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.HeaderParameter;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.QueryParameter;
import org.springdoc.core.customizers.OpenApiCustomizer;
import org.springdoc.core.customizers.RouterOperationCustomizer;
import org.springdoc.core.customizers.ServerBaseUrlCustomizer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.web.*;
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

@Configuration
@ConditionalOnProperty(prefix = "swagger", name = "open", havingValue = "true")
public class SwaggerConfig {
    @Value("${jwt.config.token-header:AUTH-TOKEN}")
    private String tokenHeader;
    @Value("${server.servlet.context-path:}")
    private String contextPath;
    @Bean
    public OpenAPI restfulOpenAPI() {
        //配置认证、请求头参数
        Components components = new Components();
        components.addParameters("globalHeader", new HeaderParameter().required(true).name(tokenHeader).description("").schema(new StringSchema()).required(true));
        components.addParameters("appId",new QueryParameter().description("公众号APPID").required(true).name("appId").schema(new StringSchema()).required(true));
        components.addParameters("secret",new QueryParameter().description("公众号SECRET").required(false).name("secret").schema(new StringSchema()).required(false));

        return new OpenAPI(SpecVersion.V31)
                .components(components)
                .info(new Info().title("微信接口代理 API")
                        .description("微信接口代理 API")
                        .version("v0.0.1")
                        .license(new License().name("Apache 2.0").url("http://springdoc.org")))
                .externalDocs(new ExternalDocumentation()
                        .description("SpringDoc Wiki Documentation")
                        .url("https://springdoc.org/v2"));
    }

    @Bean
    public OpenApiCustomizer customerGlobalHeaderOpenApiCustomizer() {
        return openApi -> {
            Paths paths = openApi.getPaths();
            //添加全局的请求头参数
            paths.values().stream().flatMap(pathItem -> pathItem.readOperations().stream())
                    .forEach(operation -> {
                        operation.addParametersItem(new HeaderParameter().$ref("#/components/parameters/globalHeader"));
                        operation.addParametersItem(new QueryParameter().$ref("#/components/parameters/appId"));
                        operation.addParametersItem(new QueryParameter().$ref("#/components/parameters/secret"));

                    });
        };
    }

    /*
     * 下面两个bean需要结合使用 前者是在接口地址中拼接contextPath前缀  后者是在baseUrl中取消contextPath
     * 由于OpenAPI3的UI提交请求时 是使用ServerBaseUrl+接口Path进行请求故需要使用以下两个Customizer完成操作
     * @date  2023/6/5 下午6:28
     * @author  jim.lee
     */

    /**
     * <p>由于Openapi3的api-docs接口中的path不会拼接contextPath,故需要使用customizer完成拼接</p>
     * <p>否则导入API-FOX后无法正常请求</p>
     * @date  2023/6/5 下午6:31
     * @author  jim.lee
     */
    @Bean
    public RouterOperationCustomizer routerOperationCustomizer(){
        return (routerOperation, handlerMethod) -> {
            //在所有接口地址上增加contextPath
            routerOperation.setPath(Optional.ofNullable(contextPath).orElseGet(()->"")+routerOperation.getPath());
            return routerOperation;
        };
    }
    @Bean
    public ServerBaseUrlCustomizer serverBaseUrlCustomizer(){
        //在serverBaseUrl中取消contextPath
        return serverBaseUrl -> serverBaseUrl.substring(0,serverBaseUrl.indexOf(contextPath));
    }


    @Bean
    public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
        Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
        return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping);
    }
    private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
        return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
    }
}

